package com.atguigu.guli.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubjectData;
import com.atguigu.guli.service.edu.listener.ExcelSubjectDataListener;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-07-26
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void importSubjects(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream())
                    .head(ExcelSubjectData.class)
                    .sheet(0)
                    .registerReadListener(new ExcelSubjectDataListener(baseMapper))
                    .doRead();

        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR,e);
        }
    }

    @Override
    public List<Subject> getNestedSubjects() {
        //查询一级和它的二级分类的嵌套集合
        /*方式1：自定义sql[]
          方式2：查询表的所有数据（包含一级和二级分类数据），在业务代码中通过pid关联数据
        * */

        List<Subject> subjects = baseMapper.selectList(null);
        //挑选出一级分类，将它们存储在map集合中
        Map<String, Subject> pSubjectMap = new HashMap<>();
        for (Subject subject : subjects) {
            if ("0".equals(subject.getParentId())){
                pSubjectMap.put(subject.getId(),subject);
            }
        }

        for (Subject subject : subjects) {
            Subject pSubject = pSubjectMap.get(subject.getParentId());
            if (pSubject != null){
                pSubject.getChildren().add(subject);
            }
        }
        return new ArrayList<>(pSubjectMap.values());
    }
}
